﻿using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Web.Common;
using Web.Filters;

namespace Web.Controllers.API
{
    public class StockController : ApiController
    {

        /// <summary>
        /// 创建仓库
        /// </summary>
        /// <param name="UserCode">商品ID</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult InsertStock([FromBody]Models.API.Param.StockModel entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.UserCode.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.FullName.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            try
            {
                SqlParameter[] parameters = {
                    new SqlParameter("@Parid","00000"),//父节点ID
                    new SqlParameter("@DbName","stock"),
                    new SqlParameter("@UserCode",entity.UserCode.ToString()),//编号
                    new SqlParameter("@FullName",entity.FullName.ToString()),//名称
                    new SqlParameter("@Name",""),//简名
                    new SqlParameter("@Comment",""),//
                    new SqlParameter("@LinkMan",""),//
                    new SqlParameter("@Tel",""),//
                    new SqlParameter("@Address",""),//
                    new SqlParameter("@PyCode",""),//
                    new SqlParameter("@STypeID","00001"),//
                    new SqlParameter("@job",""),//
                    new SqlParameter("@mobile",""),//
                    new SqlParameter("@sheng",""),//
                    new SqlParameter("@shi",""),//
                    new SqlParameter("@xian",""),//
                    new SqlParameter("@postcode",""),//
                };

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertK", parameters, out resultCount);

                if (resultCount == 0)
                {
                    string strSQL = "select typeid from Stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                    string kypeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

                    SqlParameter[] param = {
                    new SqlParameter("@CargoID",""),//父节点ID
                    new SqlParameter("@UserCode",entity.UserCode),//编号
                    new SqlParameter("@FullName",entity.FullName + "默认货位"),//名称
                    new SqlParameter("@KtypeID",kypeid),//
                    new SqlParameter("@Comment",entity.FullName + "默认货位"),//
                    new SqlParameter("@ControlType","Add"),//
                    new SqlParameter("@isDefault",1)
                    };

                    resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_CargoTypeEdit", param, out resultCount);
                }

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 查询仓库
        /// </summary>
        /// <param name="UserCode">仓库ID</param>
        /// <param name="Name">名称</param>.
        /// <param name="Delfg">删除标识</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页大小</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SelectStock(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            try
            {
                strSQL = "";
                strSQL += "select ";
                strSQL += "  parid ";
                strSQL += " ,UserCode ";
                strSQL += " ,FullName ";
                strSQL += " ,Name ";
                strSQL += " ,Comment ";
                strSQL += " ,deleted ";
                strSQL += " ,PyCode ";
                strSQL += " from Stock ";
                strSQL += " where 1=1 ";

                string strsqlcount = "";
                strsqlcount += "select count(*) ";
                strsqlcount += " from Stock ";
                strsqlcount += " where 1=1 ";

                if (null != mydyobj.UserCode && !string.IsNullOrWhiteSpace(mydyobj.UserCode.ToString()))
                { 
                    strSQL += " and UserCode = N'" + mydyobj.UserCode.ToString().Replace("'", "''") + "'";
               strsqlcount += " and UserCode = N'" + mydyobj.UserCode.ToString().Replace("'", "''") + "'";
                }
                if (null != mydyobj.Name && !string.IsNullOrWhiteSpace(mydyobj.Name.ToString())) { 
                    strSQL += " and (FullName like '%" + mydyobj.Name.ToString() + "%' or Name like '%" + mydyobj.Name.ToString() + "%')";
                strsqlcount += " and (FullName like '%" + mydyobj.Name.ToString() + "%' or Name like '%" + mydyobj.Name.ToString() + "%')";
                }
                if (null != mydyobj.PyCode && !string.IsNullOrWhiteSpace(mydyobj.PyCode.ToString()))
                { 
                    strSQL += " and PyCode like '%" + mydyobj.PyCode.ToString() + "%'";
                strsqlcount += " and PyCode like '%" + mydyobj.PyCode.ToString() + "%'";
                }
                if (null != mydyobj.Delfg && "0".Equals(mydyobj.Delfg.ToString())) {
                    strSQL += " and deleted = '0'";
                strsqlcount += " and deleted = '0'";
                }

                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strsqlcount));


                strSQL += " order by typeid asc ";

                if (!"0".Equals(mydyobj.PageIndex.ToString()) && !"0".Equals(mydyobj.PageSize.ToString()))
                {
                    strSQL += " offset " + (Convert.ToInt32(mydyobj.PageIndex.ToString()) - 1) * Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows fetch next " + Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows only";
                }

                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
              //  result.TotalRows = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        [HttpPost]
        public IHttpActionResult QueryCargos(Models.API.Param.QueryOrderInput m)
        {
            string strSQL="";
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            try
            {
                if (Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle("select count(*) from Stock where usercode='" + m.KtypeCode + "' and deleted=0")) == 0)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "未找到仓库";
                    return Json(result);
                }
                string KtypeID= db.GetSingle("select typeid from Stock where usercode='" + m.KtypeCode + "' and deleted=0").ToString();
                strSQL = @"select CargoID,UserCode,FullName,Comment,IsDefault from CargoType where deleted=0 and KtypeID='"+KtypeID+"'";
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
                //  result.TotalRows = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

    }
}